import "dart:convert";

import "package:ct_pa_majordomo/config/extension.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/user/create_apartment/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/router/routes.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:flutter/cupertino.dart";
import "package:provider/provider.dart";

class RouterInterceptor extends NavigatorObserver {

  @override
  void didPush(Route route, Route? previousRoute) {
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      checkHasApartment(route);
    });
    super.didPush(route, previousRoute);
  }

  void checkHasApartment(Route route) async {
    print("路由拦截>>>>>>>>>>>>${route.settings}");
    // dynamic memberId = Provider.of<CommonState>(context).apartment?["memberId"];
    String? token = storage.getString("token") ?? "";
    String? apartment = storage.getString("apartment") ?? "";
    if (token.isNotEmpty) {
      if (route.settings.name == Keys.LOGIN) {
        Stacker.pushReplacementNamed(Keys.MAIN);
      } else {
        if (apartment.isEmpty && !Routes.whiteList.contains(route.settings.name)) {
          Map resData = await apartmentApi.getApartmentInfo();
          if (resData["data"] == null) {
            Stacker.pushReplacementNamed(Keys.CREATE_APARTMENT);
          } else {
            storage.setString("apartment", jsonEncode(resData["data"]));
          }
        }
      }
    } else {
      Stacker.pushReplacementNamed(Keys.LOGIN);
    }
    return null;
  }
}